package com.store.app.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.easeui.model.UserEventBean;
import com.store.app.BaseActivity;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.adapter.MemberListAddContactAdapter;
import com.store.app.bean.CreateGroupBean;
import com.store.app.bean.MemberInfoBean;
import com.store.app.http.Stores;
import com.store.app.hyphenate.Constant;
import com.store.app.imlife.activity.ChatActivity;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2017/3/20.
 * 选择联系人
 */
public class AddContactsActivity extends BaseActivity implements View.OnClickListener, IOnHttpListener {
    private ImageView public_ll_return;
    private TextView tvTitle;
    private TextView public_tv_right;
    private CheckBox cb_all;
    private ListView lv_members;
    private String groupid;
    private LinearLayout public_ll_right;
    private List<MemberInfoBean> memberInfoBeanList;
    private NetRequest netRequest;
    private MemberListAddContactAdapter memberListAdapter;
    private List<MemberInfoBean> noChangeMemberInfoBeanList;
    private EditText et_member_search;
    private AlertDialog dialog;
    //type=0是创建群  type=1是群加人
    private int type = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_contact);
        groupid = getIntent().getStringExtra("groupid");
        type = getIntent().getIntExtra("type", 0);
        initView();
        initData();
    }

    public void initData() {
        netRequest = new NetRequest(this);
        memberInfoBeanList = new ArrayList<>();
        noChangeMemberInfoBeanList = new ArrayList<>();
        memberListAdapter = new MemberListAddContactAdapter(this, memberInfoBeanList);
        lv_members.setAdapter(memberListAdapter);
        lv_members.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                memberInfoBeanList.get(position).setSelect(!memberInfoBeanList.get(position).isSelect());
                boolean isCheck = memberInfoBeanList.get(position).isSelect();
                //如果选中的是全部，则遍历将所有的都打钩
                if (memberInfoBeanList.get(position).getNick_name().equals("全部")) {
                    if (isCheck) {
                        for (int i = 0; i < memberInfoBeanList.size(); i++) {
                            memberInfoBeanList.get(i).setSelect(true);
                        }
                    } else {
                        for (int i = 0; i < memberInfoBeanList.size(); i++) {
                            memberInfoBeanList.get(i).setSelect(false);
                        }
                    }
                }
                //如果不是第一个，说明选中正常会员，则判断是否全部选中，如果是，则全选要钩上，如果不是，全选要取消
                else {
                    if (TextUtils.isEmpty(et_member_search.getText().toString().trim())) {

                        //选中某个
                        boolean ifAllChoose = true;
                        for (int i = 0; i < memberInfoBeanList.size(); i++) {
                            if (i == 0) {
                                continue;
                            }
                            if (!memberInfoBeanList.get(i).isSelect()) {
                                ifAllChoose = false;
                            }
                        }
                        if (ifAllChoose) {
                            memberInfoBeanList.get(0).setSelect(true);
                        } else {
                            memberInfoBeanList.get(0).setSelect(false);
                        }
                    }
                }
                memberListAdapter.notifyDataSetChanged();
            }
        });

        if (type == 0) {
            netRequest.requestGetRelConsumerList(1, MainActivity.member_id);
            tvTitle.setText("创建群聊");
        } else if (type == 1) {
            netRequest.requestHXgetAddibleUsersForChatGroup(3, groupid);
            tvTitle.setText("添加联系人");
        }
    }

    private void initView() {
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        public_tv_right = (TextView) findViewById(R.id.public_tv_right);
        public_tv_right.setText("确定");
        public_ll_right = (LinearLayout) findViewById(R.id.public_ll_right);
        public_ll_right.setVisibility(View.VISIBLE);
        public_ll_right.setOnClickListener(this);
        cb_all = (CheckBox) findViewById(R.id.cb_all);
        lv_members = (ListView) findViewById(R.id.lv_members);
        public_ll_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        et_member_search = (EditText) findViewById(R.id.et_member_search);
        et_member_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                //遍历搜索
                if (et_member_search.getText().toString().length() > 0) {
                    checkData();
                } else {
                    memberInfoBeanList.clear();
                    memberInfoBeanList.addAll(noChangeMemberInfoBeanList);
                    memberListAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void checkData() {
        memberInfoBeanList.clear();
        String searchContent = et_member_search.getText().toString().trim();
        for (int i = 0; i < noChangeMemberInfoBeanList.size(); i++) {
            if (noChangeMemberInfoBeanList.get(i).getMobile().contains(searchContent)) {
                memberInfoBeanList.add(noChangeMemberInfoBeanList.get(i));
            }
        }
        memberListAdapter.notifyDataSetChanged();
    }

    EditText addmember_edit;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击了确定
            case R.id.public_ll_right:
                if (type == 0) {
                    final JSONArray jsonArray = getCurrentChooseContacts();
                    if (jsonArray.length() == 0) {
                        ToastTools.showShort(this, "请选择联系人!");
                        return;
                    }
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                    dialogBuilder.create();
                    LayoutInflater inflater = LayoutInflater.from(this);
                    View view = inflater.inflate(R.layout.addmemberdialog, null);
                    TextView tv_cancle = (TextView) view.findViewById(R.id.balandia_cancle);
                    TextView tv_check = (TextView) view.findViewById(R.id.balandia_check);
                    addmember_edit = (EditText) view.findViewById(R.id.addmember_edit);
                    tv_cancle.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    tv_check.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            String gropname = addmember_edit.getText().toString();
                            if (TextUtils.isEmpty(gropname)) {
                                Toast.makeText(AddContactsActivity.this, "请输入创建群的名称！", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            dialog.dismiss();
                            String membersInfo = jsonArray.toString();
                            Log.v("zyl", "membersInfo:" + membersInfo);
                            if (!TextUtils.isEmpty(LocationApplication.im_user_id)) {
                                showProgressDialog("", "正在创建群聊");
                                netRequest.requestHXCreateChatGroupWithMembers(2, gropname, "此群由" + Stores.contact_person + "创建", LocationApplication.im_user_id, membersInfo);
                            } else {
                                ToastTools.show(AddContactsActivity.this, "请重新登录,自动激活此权限", Toast.LENGTH_SHORT);
                            }
                        }
                    });
                    dialogBuilder.setView(view);
                    dialog = dialogBuilder.show();
                } else if (type == 1) {
                    final JSONArray jsonArray = getCurrentChooseContacts();
                    if (jsonArray.length() == 0) {
                        ToastTools.showShort(this, "请选择联系人!");
                        return;
                    }
                    String membersInfo = jsonArray.toString();
                    if (!TextUtils.isEmpty(LocationApplication.im_user_id)) {
                        netRequest.requestHXaddBatchUsersToChatGroup(5, groupid, membersInfo);
                    } else {
                        ToastTools.show(AddContactsActivity.this, "请重新登陆,自动激活此权限", Toast.LENGTH_SHORT);
                    }
                }
                break;
        }
    }

    /**
     * 获取当前选中联系人
     */
    public JSONArray getCurrentChooseContacts() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < memberInfoBeanList.size(); i++) {
            if (memberInfoBeanList.get(i).isSelect() && !memberInfoBeanList.get(i).getNick_name().equals("全部")) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("member_type_key", "consumer");
                    jsonObject.put("member_id", memberInfoBeanList.get(i).getConsumer_id() + "");
                    jsonObject.put("nickname", memberInfoBeanList.get(i).getNick_name() + "");
                    jsonObject.put("head_pic_path", memberInfoBeanList.get(i).getHead_pic_path() + "");
                    jsonArray.put(jsonObject);
                } catch (JSONException E) {
                }
            }
        }
        return jsonArray;
    }

    @Override
    public void onAfinalFail() {
        showToast("请检查本地网络!");
        dismissProgressDialog();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        dismissProgressDialog();
        //查询会员列表
        if (requestId == 1 || requestId == 3) {
            try {
                memberInfoBeanList.clear();
                JSONObject jsonObject = new JSONObject(result);
                Map<String, String> map = Utils.getMapForJson(jsonObject.getString("doc_url"));//保存urlmap
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                if(jsonArray.length()==0){
                    return;
                }
                MemberInfoBean tempBean = new MemberInfoBean();
                tempBean.setConsumer_id("");
                tempBean.setNick_name("全部");
                tempBean.setSelect(false);
                tempBean.setMobile("");
                memberInfoBeanList.add(tempBean);
                noChangeMemberInfoBeanList.add(tempBean);

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    MemberInfoBean memberInfoBean = new MemberInfoBean();
                    memberInfoBean.setConsumer_id(jsonObject1.getString("consumer_id"));
                    memberInfoBean.setNick_name(jsonObject1.getString("nick_name"));
                    String pic_head = map.get(jsonObject1.getString("head_pic_path"));
                    memberInfoBean.setMobile(jsonObject1.optString("mobile"));
                    if (TextUtils.isEmpty(pic_head)) {
                        memberInfoBean.setHead_pic_path("");
                    } else {
                        memberInfoBean.setHead_pic_path(pic_head);
                    }
                    memberInfoBean.setSelect(false);
                    memberInfoBeanList.add(memberInfoBean);
                    noChangeMemberInfoBeanList.add(memberInfoBean);
                }
                Log.v("zyl", "集合大小：" + memberInfoBeanList.size());
                memberListAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //创建群
        else if (requestId == 2) {
            Gson gson = new Gson();
            CreateGroupBean createGroupBean = gson.fromJson(result, CreateGroupBean.class);
            String id = createGroupBean.getId();
            if (!TextUtils.isEmpty(id)) {
                Intent intent = new Intent(this, ChatActivity.class);
                intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
                intent.putExtra("userId", id);
                startActivity(intent);
                finish();
            } else {
                ToastTools.show(this, "获取不到群号", Toast.LENGTH_SHORT);
            }
        }
        //添加联系人成功
        else if (requestId == 5) {
            EventBus.getDefault().post(new UserEventBean("", 1));
            ToastTools.show(this, "添加联系人成功！", Toast.LENGTH_SHORT);
            AddContactsActivity.this.finish();
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        dismissProgressDialog();
        showToast(msg);
    }
}
